package com.example.springcloud;

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 控制层
 *
 * @author csp 2023-02-14
 */
@org.springframework.stereotype.Controller
public class Controller {


    @GetMapping("userInfo")
    @ResponseBody
    public String userInfo(Authentication authentication) {
        return authentication.getName() + "登录成功！！！";
    }

    @GetMapping("getCodeChallenge")
    @ResponseBody
    public String getCodeChallenge(@RequestParam String verifier) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(verifier.getBytes(StandardCharsets.US_ASCII));
        String encodedVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
        return encodedVerifier;
    }

    @GetMapping("getCodeVerifier")
    @ResponseBody
    public String getCodeVerifier() {
        SecureRandom sr = new SecureRandom();
        byte[] code = new byte[32];
        sr.nextBytes(code);
        String verifier = Base64.getUrlEncoder().withoutPadding().encodeToString(code);
        return verifier;
    }

    @GetMapping("login")
    public String login() {
        return "index";
    }


    @PostMapping("login")
    @ResponseBody
    public String loginPc(String username, String password) {
        return username + "登录成功！！！";
    }

}
